// pages/xiang_qing/xiang_qing.js
import {request} from "../../utils/http.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statis:1,
    goodsid:"",
    carouse:[],
    bigimage:"",
    image:"",
    money:"",
    name:"",
    gueige:"",
    time:"",
    creat:"",
    leixing:"",
    text:"",
    totalSeconds: 10000, // 倒计时时间（单位：秒）
    hours: '00',
    minutes: '00',
    seconds: '00',
    nums:'1',
  },
  
  back(){
    wx.navigateBack();
  },
  click(e){
    this.setData({
      statis:e.currentTarget.id
    })
  },
  goche(){
    wx.switchTab({
      url: '/pages/go_wu_che_fenlei/go_wu_che_fenlei',
    })
  },
  share(){
    wx.showModal({
      title: "分享成功！",
      showCancel: false
    });
  },
  startCountdown() {
    let that = this;
    let timer = setInterval(() => {
      let totalSeconds = that.data.totalSeconds - 1;

      if (totalSeconds < 0) {
        clearInterval(timer); // 清除定时器
        wx.showToast({
          title: '倒计时结束！',
          icon: 'none',
        });
        return;
      }

      // 计算时、分、秒
      let hours = Math.floor(totalSeconds / 3600);
      let minutes = Math.floor((totalSeconds % 3600) / 60);
      let seconds = totalSeconds % 60;

      // 更新数据
      that.setData({
        totalSeconds,
        hours: that.padZero(hours),
        minutes: that.padZero(minutes),
        seconds: that.padZero(seconds),
      });
    }, 1000); // 每 1 秒执行一次
  },
  padZero(num) {
    return num < 10 ? '0' + num : num; // 补零
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.startCountdown();
    console.log("======");
    request({
      url: "/dianshang/goods/"+options.id,
      header: {
        "authorization": getApp().globalData.authorization
      }
    }).then((data)=>{
      if(data.code=200){
        console.log(data);
        this.setData({
          bigimage:data.data.bigimage,
          image:data.data.image,
          goodsid:data.data.id,
          money:data.data.money,
          name:data.data.name,
          gueige:data.data.gueige,
          time:data.data.time,
          creat:data.data.creat,
          leixing:data.data.leixing,
          text:data.data.text,
        })
      }
    })
    request({
      url: "/dianshang/carousel/list?goodsid="+options.id,
      method: "Get",
      header:{
        "authorization": getApp().globalData.authorization
      }
    }).then((data)=>{
      console.log("--------");
      console.log(data);
      if(data.code=200){
        this.setData({
          carouse:data.rows
        })
      }
    })
  },

  onChange(e) {
    const newValue = e.detail;
    this.setData({
      nums: newValue,
    });
  },
  gobuy(e){
    const goodsid = e.currentTarget.dataset.goodsid;
    const nums = this.data.nums;
    request({
      url:"/dianshang/cart",
      method:"POST",
      data:{
        goodsid:goodsid,
        nums:nums,
        userid:getApp().globalData.userInfo.userId,
        del:0
      },
      header: {
        "authorization": getApp().globalData.authorization
      }
    }).then((data)=>{
      if (data.code==200) {
        getApp().globalData.nums++;
        wx.setTabBarBadge({
          index:2,
          text:getApp().globalData.nums.toString(),
        });
        wx.showModal({
          title: "添加成功！",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/go_wu_che_fenlei/go_wu_che_fenlei', 
              });
            }
          }
        });
      }
    })
  },
  
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },


  gobuy1(e) {
    console.log("123456+++++++++++++++++++");
    console.log(e);
    const goodsid = e.target.dataset.goodsid;
    const nums = e.target.dataset.nums;

    console.log("goodsid"+goodsid);
    console.log("123456++++++++++++++++++");
    // 添加商品到购物车
    request({
      url: "/dianshang/cart",
      method: "POST",
      data: {
        goodsid:goodsid,
        userid: getApp().globalData.userInfo.userId,
        nums:nums,
        del: 0,
      },
      header: {
        authorization: getApp().globalData.authorization,
      },
    })
      .then((data) => {
        if (data.code == 200) {
          // 更新全局购物车数量
          getApp().globalData.nums++;
          wx.setTabBarBadge({
            index: 2,
            text: getApp().globalData.nums.toString(),
          });
          // 查询购物车列表
          return this.getCartList();
        } else {
          throw new Error("加入购物车失败");
        }
      })
      .then((cartData) => {
        // 获取购物车数据并跳转页面
        const goods = cartData.rows;
        if (goods && goods.length > 0) {
          wx.setStorageSync("goods", goods);
          wx.navigateTo({
            url: "/pages/go_wu_che/go_wu_che",
          });
        } else {
          wx.showToast({
            title: "购物车为空，请重试",
            icon: "none",
          });
        }
      })
      .catch((error) => {
        console.log("流程出错：", error);
        wx.showToast({
          title: "操作失败，请重试",
          icon: "none",
        });
      });
  },
  
  getCartList() {
    return request({
      url: "/dianshang/cart/listbyuserId?userid=" + getApp().globalData.userInfo.userId,
      header: {
        authorization: getApp().globalData.authorization,
      },
    });
  },
    
})